<script setup>
import * as Cesium from "cesium";
import { onMounted, ref } from "vue";
import RenderUtil from "../utils/RenderUtil";
import CustomPrimitive from "../utils/CustomPrimitive";
import MyPrimitive from "../primitives/MyPrimitive";
import getCesiumHeat from '../utils/CesiumHeat';
import HeatmapPrimitive from "@/primitives/HeatmapPrimitive1.js";
import data from '@/assets/last-all-airbox';

let viewer, baseLayer, enumLayer;
const tianditutkArr = [
  "590447cdbdf97775b57588a69ebb903d",
  "75f1cc913e8d68f7bd4b6f6383f78ceb",
  "4c4c0f03b0bdb58811f657fec0c09eb5",
];
// ['590447cdbdf97775b57588a69ebb903d', '75f1cc913e8d68f7bd4b6f6383f78ceb', '4c4c0f03b0bdb58811f657fec0c09eb5']
const tianditutk =
  tianditutkArr[Math.floor(Math.random() * tianditutkArr.length)];
Cesium.Ion.defaultAccessToken =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhZjE5ZTBhZC00YzE1LTQyMWYtOWM4MC00NmFlZjZhOGI3ZDciLCJpZCI6MTI4NTI2LCJpYXQiOjE2OTg4MzczOTN9.26EHXec7Ufty_B4e5_YWcB0t--zlquly7r66WVSS9wE";
// 设置Cesium默认视角
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
  108.4,
  21.3,
  129.3,
  48.6
);
// 添加网格三维热力图
function addHeatMap3D(type = 'triangle') {
  viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(108, 34, 50000),
    orientation: {
      heading: Cesium.Math.toRadians(0), // 方向
      pitch: Cesium.Math.toRadians(-90), // 倾斜角度
      roll: Cesium.Math.toRadians(0),
    },
  })
  // 随机生成数据
  let heatMaplist = [];
  for (let i = 0; i < 200; i++) {
    heatMaplist.push({
      "lnglat": [108 + Math.random() * .1 * (Math.random() > 0.5 ? 1 : -1), 34 + Math.random() * .1 * (Math.random() > 0.5 ? 1 : -1)],
      "value": 1000 * Math.random()
    })
  }
  return new HeatmapPrimitive(viewer, {
    list: heatMaplist,
    raduis: 16,
    baseHeight: 500,
    primitiveType: type === 'triangle' ? "TRNGLE" : "LINES", //格网（LINES）和三角面（TRIANGLES）
    mapDom: document.getElementById(viewer.container.id),
    gradient: {
      ".3": "blue",
      ".5": "green",
      ".7": "yellow",
      ".95": "red"
    }
  })
}
// 添加自定义三维热力图
function addCustomHeatMap3D(type = 'triangle') {
  console.log("customData", data);
  let bbox = [120.106188593, 21.9705713974, 121.951243931, 25.2954588893];
  viewer.camera.flyTo({
    destination: Cesium.Rectangle.fromDegrees(...bbox),
    duration: 0.1,
  });
  const heatMaplist = data.feeds.map(({ gps_lon, gps_lat, s_d0 }) => {
    return {
      lnglat: [gps_lon, gps_lat],
      value: s_d0 * 10,
    };
  })
  return new HeatmapPrimitive(viewer, {
    list: heatMaplist,
    raduis: 16,
    baseHeight: 500,
    primitiveType: type === 'triangle' ? "TRNGLE" : "LINES", //格网（LINES）和三角面（TRIANGLES）
    mapDom: document.getElementById(viewer.container.id),
    gradient: {
      ".3": "blue",
      ".5": "green",
      ".7": "yellow",
      ".95": "red"
    }
  })
}
// 添加随机三维热力图
function addRandomHeatMap3D(type = 'triangle') {
  const heatMaplist = [
    {
      lnglat: [108.4, 34.1],
      value: 1000 * Math.random(),
    },
    {
      lnglat: [109.4, 34.5],
      value: 1000 * Math.random(),
    },
    {
      lnglat: [110.4, 34.8],
      value: 1000 * Math.random(),
    },
    {
      lnglat: [111.4, 35.8],
      value: 1000 * Math.random(),
    },
    {
      lnglat: [112.4, 35.5],
      value: 1000 * Math.random(),
    },
    {
      lnglat: [114.4, 36.5],
      value: 1000 * Math.random(),
    },
    {
      lnglat: [115.4, 36.8],
      value: 1000 * Math.random(),
    },
    {
      lnglat: [116.4, 37.8],
      value: 1000 * Math.random(),
    },
  ]
  return new HeatmapPrimitive(viewer, {
    list: heatMaplist,
    raduis: 16,
    baseHeight: 500,
    primitiveType: type === 'triangle' ? "TRNGLE" : "LINES", //格网（LINES）和三角面（TRIANGLES）
    mapDom: document.getElementById(viewer.container.id),
    gradient: {
      ".3": "blue",
      ".5": "green",
      ".7": "yellow",
      ".95": "red"
    }
  })
}
onMounted(() => {
  baseLayer = new Cesium.ImageryLayer(
    new Cesium.WebMapTileServiceImageryProvider({
      url:
        "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
        tianditutk,
      layer: "tdtImgLayer",
      style: "default",
      format: "image/jpeg",
      tileMatrixSetID: "GoogleMapsCompatible", //使用谷歌的瓦片切片方式
      show: true,
    })
  );
  viewer = new Cesium.Viewer("cesiumContainer", {
    // animation: false, // 动画小组件
    baseLayerPicker: false, // 底图组件，选择三维数字地球的底图
    fullscreenButton: false, // 全屏组件
    vrButton: false, // VR模式
    geocoder: false, // 地理编码搜索组件
    homeButton: false, // 首页，点击之后将视图跳转到默认视角
    infoBox: false, // 信息框
    sceneModePicker: false, // 场景模式，切换2D、3D和Columbus Views（CV）模式
    selectionIndicator: false, // 是否显示选取指示器组件
    // timeline: false, // 时间轴
    navigationHelpButton: false, // 帮助提示，如何操作数字地球
    navigationInstructionsInitiallyVisible: false,
    // terrain: new Cesium.Terrain.fromWorldTerrain({
    //   url: Cesium.IonResource.fromAssetId(3956),
    //   requestWaterMask: true,    // 请求水体效果所需要的海水波浪数据
    //   requestVertexNormals: true   // 请求地形照明数据
    // }),
    baseLayer,
    contextOptions: {
      requestWebgl2: true, // 开启webgl2渲染
    },
  });

  enumLayer = new Cesium.ImageryLayer(
    new Cesium.WebMapTileServiceImageryProvider({
      url:
        "http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
        tianditutk,
      layer: "tdtCiaLayer",
      style: "default",
      format: "image/jpeg",
      tileMatrixSetID: "GoogleMapsCompatible", //使用谷歌的瓦片切片方式
      show: true,
    })
  );
  viewer.imageryLayers.add(enumLayer);
  window.baseLayer = baseLayer;
  window.viewer = viewer;
  window.enumLayer = enumLayer;
  // 添加网格三维热力图
  // addHeatMap3D()
  // 添加自定义三维热力图
  addCustomHeatMap3D()
  // 添加随机三维热力图
  // addRandomHeatMap3D()
});
</script>

<template>
  <div id="cesiumContainer"></div>
</template>

<style lang="scss">
#cesiumContainer {
  width: 100vw;
  height: 100vh;
  position: relative;

  .cesium-viewer-bottom {
    visibility: hidden;
  }
}
</style>
